package cn.ac.jaas.isc.vegetable.pbms.service.impl;

import cn.ac.jaas.isc.vegetable.common.core.util.R;
import cn.ac.jaas.isc.vegetable.pbms.api.entity.ArcBase;
import cn.ac.jaas.isc.vegetable.common.security.service.VegetableUser;
import cn.ac.jaas.isc.vegetable.common.security.util.SecurityUtils;
import cn.ac.jaas.isc.vegetable.pbms.api.entity.ArcEquipmentType;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import cn.ac.jaas.isc.vegetable.pbms.mapper.ArcBaseMapper;
import cn.ac.jaas.isc.vegetable.pbms.service.ArcBaseService;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;

/**
 * 基地表
 *
 * @author 张高昌
 * @date 2022-05-01 15:57:08
 */
@Service
@AllArgsConstructor
public class ArcBaseServiceImpl extends ServiceImpl<ArcBaseMapper, ArcBase> implements ArcBaseService {

    @Transactional(rollbackFor = Exception.class)
    @Override
    public R saveBase(ArcBase arcBase) {
        ArcBase nameModel = baseMapper.selectOne(Wrappers.<ArcBase>query().lambda().eq(ArcBase::getBaseName, arcBase.getBaseName()));
        if (nameModel != null) {
            return R.failed("基地名称已存在！");
        }
        VegetableUser user = SecurityUtils.getUser();
        arcBase.setCreateTime(LocalDateTime.now());
        arcBase.setCreateUser(user.getId());
        baseMapper.insert(arcBase);
        return R.ok(true);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public R updateBaseById(ArcBase arcBase) {
        LambdaQueryWrapper<ArcBase> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(ArcBase::getBaseName, arcBase.getBaseName())
                .ne(ArcBase::getBaseId, arcBase.getBaseId());
        ArcBase nameModel = baseMapper.selectOne(wrapper);
        if (nameModel != null) {
            return R.failed("设备类型名称已存在！");
        }
        VegetableUser user = SecurityUtils.getUser();
        arcBase.setUpdateTime(LocalDateTime.now());
        arcBase.setUpdateUser(user.getId());
        baseMapper.updateById(arcBase);
        return R.ok(true);
    }

    @Override
    public R removeBaseById(Integer baseId) {
        ArcBase arcBase = baseMapper.selectById(baseId);
        if (arcBase == null) {
            return R.failed("基地不存在");
        }
        Integer status = arcBase.getStatus();
        if (status == 1){
            return R.failed("基地当前状态为已启动，无法删除");
        }
        baseMapper.deleteById(baseId);
        return R.ok(true);
    }
}
